package com.ygxsk.carhome.ui.livefee;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mmkv.MMKV;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.FeeLiveOtherType;
import com.ygxsk.carhome.enumwrap.FeePayType;
import com.ygxsk.carhome.enumwrap.PropertyMentType;
import com.ygxsk.carhome.event.EventPay;
import com.ygxsk.carhome.event.EventPaymentSubmint;
import com.ygxsk.carhome.helper.PushConstants;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.AlipayPayBean;
import com.ygxsk.carhome.response.FeePayTypeListBean;
import com.ygxsk.carhome.response.PayParameterResult;
import com.ygxsk.carhome.response.PaymentFeeBean;
import com.ygxsk.carhome.response.PropertyPaymentBean;
import com.ygxsk.carhome.response.WechatPayBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusWithFeePayTypeListBean;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.PropertyPaymentAdapter;
import com.ygxsk.carhome.ui.paintbook.PayResult;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-12-23  08:38
 * @Description:物业缴费-缴费支付页面
 */
public class PaymentFeeActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshlayoutinpaymentfees)
    SmartRefreshLayout refreshLayoutInPayMentFees;

    @BindView(R.id.recyclerviewinpaymentfee)
    RecyclerView recyclerViewInPaymentFee;

    //底部的应付金额的，携带羊角标志红色
    @BindView(R.id.textviewamountfee)
    TextView textviewFeiYongAmount;

    //优惠券的三种状态提示==================================
    private String messageCouponSelect = "请选择优惠券";
    private String messageNoCoupon = "没有可用优惠券";
    //====================================================

    //缴费的弹窗
    private BasePopupView basePopupView_payType;


//    /**
//     * 从物业缴费列表携带过来的支付总额
//     */
//    private String priceTotal;

    /**
     * 上传缴费id信息
     */
    private ArrayList<String> housePaymentIdsPass = new ArrayList<>();

    //支付方式列表的外侧总列表,和水费、电费 保持一致的字段 FeePayTypeListBean
    private ArrayList<FeePayTypeListBean> feePayTypeListBeanArrayListDatas = new ArrayList<>();

    /**
     * 主界面数据内容
     */
    private ArrayList<PropertyPaymentBean> mDatasResources = new ArrayList<>();

    /**
     * 获取默认的支付方式，后台给定的，但是真实支付 还是要认真区分 是微信支付还是支付宝支付
     */
    private String payTypeCode;

    /**
     * 预付单号。可以单独拿出来
     */
    private String beforeReceiptNo;

    //缴费列表适配器内容
    private PropertyPaymentAdapter propertyPaymentAdapter;

    private IWXAPI mWinXinApi;

    //支付宝的SDK支付标识
    private static final int SDK_PAY_FLAG = 12;


    @OnClick({R.id.buttontopay})
    public void clickInPaymentFeeBtom(View view) {

        switch (view.getId()) {

            case R.id.buttontopay: {

                if (!DoubleClickListener.isFastDoubleClick()) {

                    if (flag_jumpfrom_where == FeeLiveOtherType.TYPE_PROPERTY.getIndex()) {

                        //弹出支付弹窗，使用和水费电费相同的缴费弹窗。
                        basePopupView_payType = new XPopup.Builder(PaymentFeeActivity.this)
                                .hasShadowBg(true)
                                //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面;
                                .isViewMode(true)
                                //.autoDismiss(false)
                                //.isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                                //.isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                                //.dismissOnTouchOutside(true)
                                //.notDismissWhenTouchInView()
                                .asCustom(new FeePayPopu(PaymentFeeActivity.this,//
                                        ExtraValue.MODIFY_EVALUATE_PAYTYPE_SELECT_PROPERTY_ACTIVITY,//标志是物业缴费过来的
                                        feePayTypeListBeanArrayListDatas))//
                                .show();

                    } else if (flag_jumpfrom_where == FeeLiveOtherType.TYPE_RENTAL.getIndex()) {

                        basePopupView_payType = new XPopup.Builder(PaymentFeeActivity.this)
                                .hasShadowBg(true)
                                //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面;
                                .isViewMode(true)
                                //.autoDismiss(false)
                                //.isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                                //.isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                                //.dismissOnTouchOutside(true)
                                //.notDismissWhenTouchInView()
                                .asCustom(new FeePayPopu(PaymentFeeActivity.this,//
                                        ExtraValue.MODIFY_EVALUATE_PAYTYPE_SELECT_RENTAL_ACTIVITY,//标志是租赁费过来的
                                        feePayTypeListBeanArrayListDatas))//
                                .show();

                    }


                }

                break;
            }

            default:
                break;
        }

    }

    /*
     * @Author:itchenqi
     * @Time:2022-03-04  10:50
     * @Description:该界面的Handler的写法
     */
    private static class BetterHandlerInPaymentFee extends Handler {

        private WeakReference<PaymentFeeActivity> mActivity;

        private BetterHandlerInPaymentFee(PaymentFeeActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            PaymentFeeActivity mCurrentActivity = mActivity.get();

            if (mCurrentActivity != null) {

                switch (msg.what) {

                    case SDK_PAY_FLAG: {//支付处理内容

                        PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                        /**
                         对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();

                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, ConstantSign.ALIPAY_SUCCESS_9000)) {

                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                            //Toast.makeText(AccountPayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
//                            CommUtils.displayToastShort(mCurrentActivity, "支付成功");

                            ToastUtils.showShort(mCurrentActivity.getResources().getString(R.string.alipay_pay_success));
//                            mCurrentActivity.gainOrderState(mCurrentActivity.payTokenForPay, 1);//支付成功跳转到结算结果页面。

                            mCurrentActivity.method_handler_success_for_alipayOrweChat();

                        } else {

                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                            //Toast.makeText(AccountPayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
//                            CommUtils.displayToastShort(mCurrentActivity, "支付失败");

                            ToastUtils.showShort(mCurrentActivity.getResources().getString(R.string.alipay_pay_error));

                            //提示失败还停留在 该支付页面，以便于选择其他支付

                        }

                        break;
                    }

//                    case FILLHEJIAMOUNT: {
//
//                        //2018年09月01日重新做刷新UI的处理
//
//                        final BigDecimal bigDecimal = CommUtils.formatComma2BigDecimal(msg.obj);
//
//                        //左侧底部的应付金额内容
//                        if (mCurrentActivity.textViewAmountFee != null) {
//
//                            mCurrentActivity.textViewAmountFee.setText(mCurrentActivity._sessionErrorActivity.getCurrencySymbol() + bigDecimal.toString());
//
//                            //第二种方式
//                        /*textViewAmountFee.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                textViewAmountFee.setText(mSession.getCurrencySymbol() + bigDecimal.toString());
//                            }
//                        });*/
//
//                        }
//
//                        break;
//                    }

//                    case METHODCLEARTEXTVIEWSELECT: {//清除优惠券的可点击选择内容
//
//                        //如下两行是原始代码，下边的是后改造的
//
//                        if (mCurrentActivity.textViewCouPonsDesAccount != null) {
//
//                            mCurrentActivity.textViewCouPonsDesAccount.setText(mCurrentActivity.messageCouponSelect);//请选择优惠券
//
//                            //箭头图片展示且可以点击内容
//                            CommUtils.setViewVisible(mCurrentActivity.imageHaveCouponsAccount);
//
//                        /*textViewCouPonsDesAccount.post(new Runnable() {
//                            @Override
//                            public void run() {
//
//                                textViewCouPonsDesAccount.setText(messageCouponSelect);//请选择优惠券
//
//                                //箭头图片展示且可以点击内容
//                                CommUtils.setViewVisible(imageHaveCouponsAccount);
//
//                            }
//                        });*/
//
//                        }
//
//
//                        if (mCurrentActivity.textviewYouhquanPriceRight != null) {//最终赋值优惠券右侧文字内容
//
//                            mCurrentActivity.textviewYouhquanPriceRight.setText("-" + mCurrentActivity._sessionErrorActivity.getCurrencySymbol() + CommUtils.formatComma2BigDecimal(new BigDecimal("0.00")));
//
//                        }
//
//                        break;
//                    }

//                    case METHODFILLTEXTVIEWSELECT: {//填充优惠券抵扣的内容，然后可点击
//
//                        //您已经选择N元的优惠券内容
//                        if (mCurrentActivity.textViewCouPonsDesAccount != null) {
//
//                            mCurrentActivity.textViewCouPonsDesAccount.setText("优惠券已抵扣" + (String) msg.obj + "元");
//
//
//                        /*textViewCouPonsDesAccount.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                textViewCouPonsDesAccount.setText("优惠券已抵扣" + (String)msg.obj + "元");
//                            }
//                        });*/
//
//                        }
//
//
//                        if (mCurrentActivity.textviewYouhquanPriceRight != null) {//最终赋值优惠券右侧文字内容
//                            mCurrentActivity.textviewYouhquanPriceRight.setText("-" + (String) msg.obj);
//                        /*textviewYouhquanPriceRight.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                textviewYouhquanPriceRight.setText("-" + (String)msg.obj);
//                            }
//                        });*/
//                        }
//
//                        break;
//                    }

//                    case METHODCLEARTEXTVIEWSELECTNOCAN: {
//
//
//                        //2018年08月10日添加有默认优惠券的内容
//                        if (mCurrentActivity.textViewCouPonsDesAccount != null) {
//
//                            mCurrentActivity.textViewCouPonsDesAccount.setText(mCurrentActivity.messageNoCoupon);//没有可用优惠券内容。
//
//                            CommUtils.setViewInvisible(mCurrentActivity.imageHaveCouponsAccount);//右侧箭头隐藏掉
//
//                        /*textViewCouPonsDesAccount.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                textViewCouPonsDesAccount.setText(messageNoCoupon);//没有可用优惠券内容。
//                                CommUtils.setViewInvisible(imageHaveCouponsAccount);//右侧箭头隐藏掉
//                            }
//                        });*/
//
//                        }
//
//                        // 右侧价格重新赋值
//                        // 最终赋值优惠券右侧文字内容仍然是0.0元
//                        if (mCurrentActivity.textviewYouhquanPriceRight != null) {
//
//                            mCurrentActivity.textviewYouhquanPriceRight.setText("-" + mCurrentActivity._sessionErrorActivity.getCurrencySymbol() + CommUtils.formatComma2BigDecimal(new BigDecimal("0.00")));
//
//
//                        }
//
//                        break;
//                    }

                    default:
                        break;
                }

            }
        }
    }


    private BetterHandlerInPaymentFee mHandler;

    private PermissionSetting mSetting;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        setContentView(R.layout.activity_payment_fee);

//        mWinXinApi = WXAPIFactory.createWXAPI(this, PushConstants.WEIXIN_APPID);//e车联微信id
//
//        if (mWinXinApi != null) {
//            mWinXinApi.registerApp(PushConstants.WEIXIN_APPID);
//            LogUtils.d("itchen--微信--registerApp");
//        }

//        if (activityPaintBookingMainBinding != null) {
//            if (activityPaintBookingMainBinding.getRoot() != null) {
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL+"activityPaintBookingMainBinding.getRoot()-->"+activityPaintBookingMainBinding.getRoot());
//                setContentView(activityPaintBookingMainBinding.getRoot());
//                super.onCreate(savedInstanceState);
//            }
//        } else {
//        }
//        activityPaintBookingMainBinding = (ActivityPaintBookingMainBinding) viewBindingParent;

        mActivityInstance = this;

        if (mHandler == null) {
            mHandler = new BetterHandlerInPaymentFee(this);
        }

        processExtraData();

        mSetting = new PermissionSetting(this);

        initloading();

        initViews();

        gainDatas();


        mCompositeDisposable.add(RxBus.getInstance()
                .toObserverable(RxBusWithFeePayTypeListBean.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusWithFeePayTypeListBean>() {

                    @Override
                    public void accept(RxBusWithFeePayTypeListBean rxBusWithFeePayTypeListBean) throws Throwable {

                        if (rxBusWithFeePayTypeListBean != null) {

                            if (rxBusWithFeePayTypeListBean.getActionFlag() == ExtraValue.MODIFY_EVALUATE_PAYTYPE_SELECT_PROPERTY_ACTIVITY) {//【标志是物业缴费过来的】；

//                           LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--customerId_upLoad-->" + customerId_upLoad);

//                                {
//                                        "image": "http://222.222.17.184:19181/resource/shop/image/pay/0.png",
//                                        "isEnable": 1,
//                                        "isOnline": 1,
//                                        "payName": "支付宝支付",
//                                        "payRate": 0.0060,
//                                        "payTypeCode": "ALIPAY_APP",
//                                        "payTypeId": 1,
//                                        "sortCode": 1
//                                },
//                                {
//                                        "image": "http://222.222.17.184:19181/resource/shop/image/pay/1.png",
//                                        "isEnable": 1,
//                                        "isOnline": 1,
//                                        "payName": "微信支付",
//                                        "payRate": 0.0060,
//                                        "payTypeCode": "WECHAT_APP",
//                                        "payTypeId": 2,
//                                        "sortCode": 2
//                                }

                                if (rxBusWithFeePayTypeListBean.getFeePayTypeListBean() != null) {

//                                    public enum FeePayType {
//                                        TYPE_ALIPAY("1", "ALIPAY_APP"),
//                                        TYPE_WECHAT("2", "WECHAT_APP");

                                    String payTypeCodeCurrent = rxBusWithFeePayTypeListBean.getFeePayTypeListBean().getPayTypeCode();
                                    payTypeCode = payTypeCodeCurrent;

                                    //取出勾选数据
//                                    ArrayList<FeeLivingExpensesWaterBean> temp = new ArrayList<>();
//                                    if (mDataResources != null && !mDataResources.isEmpty()) {
//                                        for (FeeLivingExpensesWaterBean item : mDataResources) {
//                                            boolean isChecked = item.isChecked();
//                                            if (isChecked) {
//                                                temp.add(item);
//                                            }
//                                        }
//                                    }

                                    //上传数据
//                                    ArrayList<FeeLivingExpensesWaterUpLoad> tempLikeHashMap = new ArrayList<>();
//
//                                    if (temp != null && !temp.isEmpty()) {
//
//                                        for (FeeLivingExpensesWaterBean itemUpLoad : temp) {
//                                            //水表号
//                                            String gaugeNo = itemUpLoad.getGaugeNo();
//                                            //该水表号对应的金额
//                                            BigDecimal myGaugeFinalAmount = itemUpLoad.getAmount();
//
//                                            FeeLivingExpensesWaterUpLoad feeLivingExpensesWaterUpLoad = new FeeLivingExpensesWaterUpLoad();
//                                            feeLivingExpensesWaterUpLoad.setGaugeNo(gaugeNo);
//
//                                            if (myGaugeFinalAmount != null) {
//                                                feeLivingExpensesWaterUpLoad.setFinalAmount(myGaugeFinalAmount.toString());
//                                            } else {
//                                                feeLivingExpensesWaterUpLoad.setFinalAmount(CommUtils.formatComma2BigDecimal(ConstantSign.BIGDECIMAL_ZERO).toString());
//                                            }
//
//                                            tempLikeHashMap.add(feeLivingExpensesWaterUpLoad);
//
//                                        }
//
//                                    }
//                                        String gaugeListUpLoad = JSON.toJSONString(tempLikeHashMap);
//                                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "gaugeListUpLoad-->" + gaugeListUpLoad);
                                    //itchen-->gaugeListUpLoad-->[{"finalAmount":"0.00","gaugeNo":"340119017114"},{"finalAmount":"0.00","gaugeNo":"236910010720"},{"finalAmount":"0.00","gaugeNo":"236910010716"}]
//                                        if (!TextUtils.isEmpty(gaugeListUpLoad)) {
//                                            String removeStr = gaugeListUpLoad.substring(1,gaugeListUpLoad.length()-1);

                                    if (TextUtils.equals(FeePayType.TYPE_ALIPAY.getPayTypeCode(), payTypeCodeCurrent)) {

                                        //支付宝支付
                                        methd_to_payMent_WeChatSDK_or_AlipaySDK_type_property(FeePayType.TYPE_ALIPAY.getPayTypeCode());

                                    } else if (TextUtils.equals(FeePayType.TYPE_WECHAT.getPayTypeCode(), payTypeCodeCurrent)) {

                                        //微信支付
                                        methd_to_payMent_WeChatSDK_or_AlipaySDK_type_property(FeePayType.TYPE_WECHAT.getPayTypeCode());

                                    }

                                }

                            } else if (rxBusWithFeePayTypeListBean.getActionFlag() == ExtraValue.MODIFY_EVALUATE_PAYTYPE_SELECT_RENTAL_ACTIVITY) {//标志是租赁费过来的；

                                if (rxBusWithFeePayTypeListBean.getFeePayTypeListBean() != null) {

//                                    public enum FeePayType {
//                                        TYPE_ALIPAY("1", "ALIPAY_APP"),
//                                        TYPE_WECHAT("2", "WECHAT_APP");

                                    String payTypeCodeCurrent = rxBusWithFeePayTypeListBean.getFeePayTypeListBean().getPayTypeCode();
                                    payTypeCode = payTypeCodeCurrent;

                                    if (TextUtils.equals(FeePayType.TYPE_ALIPAY.getPayTypeCode(), payTypeCodeCurrent)) {

                                        //支付宝支付
                                        methd_to_payMent_WeChatSDK_or_AlipaySDK_type_rental(FeePayType.TYPE_ALIPAY.getPayTypeCode());

                                    } else if (TextUtils.equals(FeePayType.TYPE_WECHAT.getPayTypeCode(), payTypeCodeCurrent)) {

                                        //微信支付
                                        methd_to_payMent_WeChatSDK_or_AlipaySDK_type_rental(FeePayType.TYPE_WECHAT.getPayTypeCode());
                                    }

                                }

                            }
                        }
                    }
                }));


        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {

        mWinXinApi = WXAPIFactory.createWXAPI(this, PushConstants.WEIXIN_APPID);//红色物业的微信id

        if (mWinXinApi != null) {
            mWinXinApi.registerApp(PushConstants.WEIXIN_APPID);
            //LogUtils.d("itchen--微信--registerApp");
        }

        return R.layout.activity_payment_fee;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getResources().getString(R.string.fee_pay_property));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        recyclerViewInPaymentFee.setLayoutManager(new MyLinearLayoutManager(this));
        propertyPaymentAdapter = new PropertyPaymentAdapter(R.layout.propertypaymentadapter, mDatasResources, PropertyMentType.TYPE_GO_TO_PAY.getIndex());
        recyclerViewInPaymentFee.setAdapter(propertyPaymentAdapter);
        propertyPaymentAdapter.notifyDataSetChanged();

        //其他操作
        if (refreshLayoutInPayMentFees != null) {

            refreshLayoutInPayMentFees.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            if (mDatasResources != null && !mDatasResources.isEmpty()) {
                                mDatasResources.clear();
                            }

                            if (propertyPaymentAdapter != null) {
                                propertyPaymentAdapter.notifyDataSetChanged();
                            }

                            if (NetworkUtils.isConnected()) {

                                getServerDatas(housePaymentIdsPass, false);

                            } else {

                                netWorkError();

                            }

                            refreshLayout.finishRefresh();

                        }
                    });

                }
            });
        }


    }

    @Override
    protected void gainDatas() {

        if (mDatasResources != null && !mDatasResources.isEmpty()) {
            mDatasResources.clear();
        }

        if (propertyPaymentAdapter != null) {
            propertyPaymentAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas(housePaymentIdsPass, true);

        } else {

            netWorkError();
//          setEnableLoadmore(refreshLayoutInLeadsActivity, false);

        }

    }

    private void getServerDatas(ArrayList<String> _housePaymentIds, boolean isShowLoading) {

        if (flag_jumpfrom_where == FeeLiveOtherType.TYPE_PROPERTY.getIndex()) {

            HashMap<String, Object> map = new HashMap<>();
            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
            map.put(Parameterkey.housePaymentIds, _housePaymentIds);//携带id列表信息

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.GETFINANCEGAUGEBYHOUSELIST_URL);//请求数字标识
            addLogUpLoadInfo.setUrlPath(ApiService.getFinanceGaugeByHouseList_url);//url地址
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .getBeforeReceiptNoForRemote(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                            MediaType.parse(ApiService.HEADER_JSON)))
                    .compose(PaymentFeeActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PaymentFeeBean>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                            CommUtils.checkMaterialDialog(materialDialog);
                            methodNotSuccessData(what_method, serverCode, serverMessage);
                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {

//                            if (refreshLayoutInPayMentFees.getState() == RefreshState.PullDownToRefresh) {
//                                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "正在处于下拉刷新的状态--RefreshState.PullDownToRefresh");
//                            } else {
//                                method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
//                            }

                            if (isShowLoading) {
                                method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                            }

                            loadingGone();

                        }
                    }).subscribe(new Consumer<PaymentFeeBean>() {
                        @Override
                        public void accept(PaymentFeeBean paymentFeeBean) throws Throwable {

                            method_handler_success_for_serverDatas(paymentFeeBean);

                        }
                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            //页面报错；
                            if (apiException != null) {
                                if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                    ToastUtils.showShort(apiException.getDisplayMessage());
                                }
                            }

                        }
                    });

        } else if (flag_jumpfrom_where == FeeLiveOtherType.TYPE_RENTAL.getIndex()) {


            HashMap<String, Object> map = new HashMap<>();
            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
            map.put(Parameterkey.housePaymentIds, _housePaymentIds);//携带id列表信息

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETNEWBEFORERECEIPTNO_URL);//请求数字标识
            addLogUpLoadInfo.setUrlPath(ApiService.getNewBeforeReceiptNo_url);//url地址
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .getNewBeforeReceiptNo(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                            MediaType.parse(ApiService.HEADER_JSON)))
                    .compose(PaymentFeeActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PaymentFeeBean>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                            CommUtils.checkMaterialDialog(materialDialog);
                            methodNotSuccessData(what_method, serverCode, serverMessage);
                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {

//                            CommUtils.checkMaterialDialog(materialDialog);
                            if (isShowLoading) {
                                method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                            }

                            loadingGone();

                        }
                    }).subscribe(new Consumer<PaymentFeeBean>() {
                        @Override
                        public void accept(PaymentFeeBean paymentFeeBean) throws Throwable {

                            method_handler_success_for_serverDatas(paymentFeeBean);

                        }
                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            //页面报错；
                            if (apiException != null) {
                                if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                    ToastUtils.showShort(apiException.getDisplayMessage());
                                }
                            }

                        }
                    });

        }

    }

    //物业缴费和租赁费通用 处理后台数据
    private void method_handler_success_for_serverDatas(PaymentFeeBean _paymentFeeBean) {

        CommUtils.checkMaterialDialog(materialDialog);

        if (_paymentFeeBean != null) {

            //预付单号，支付用到；
            beforeReceiptNo = _paymentFeeBean.getBeforeReceiptNo();
            //默认的支付方式 后台给定；
            payTypeCode = _paymentFeeBean.getPayTypeCode();

            //红色物业  优惠券的相关处理逻辑
//                            if (couponCustomers != null && (!couponCustomers.isEmpty())) {
//                                couponCustomers.clear();
//                            }
//
//                            //优惠券列表信息--这个和footer的布局有关
//                            ArrayList<CouponBean> couponCustomersTemp = paymentFeeBean.getCouponCustomers();
//
//                            if (couponCustomersTemp != null && (!couponCustomersTemp.isEmpty())) {
//                                couponCustomers.addAll(couponCustomersTemp);
//                            }

            //============================================================================================
            //2018年08月10日添加默认物业缴费的优惠券内容
            //填充默认优惠券的内容.需要参考AccountPayDecorActivity这个类的内容。
//                            String couponCustomerIdReceive = paymentFeeBean.getCouponCustomerId();

            BigDecimal totalAmount = _paymentFeeBean.getTotalAmount();

            // TODO: 2023-12-23 14:38 开发的时候参考红色物业的物业缴费代码逻辑
//                          theResultPayAmount = paymentFeeBean.getTotalAmount();
            String totalAmountResult = "";
            if (totalAmount != null) {
                totalAmountResult = MMKV.defaultMMKV().decodeString(ConstantSign.P_CURRENCYSYMBOL, StringUtils.getString(R.string.yangjiaocurrencysymbol)) + totalAmount.toString();
            } else {
                totalAmountResult = CommUtils.formatComma2BigDecimal(ConstantSign.BIGDECIMAL_ZERO).toString();
            }

            //应付金额
            if (textviewFeiYongAmount != null) {
                textviewFeiYongAmount.setText(totalAmountResult);
            }

            //----------------------------------------------------------------------------------------------------
            //支付方式列表
            //bug 2023-12-23 16:57:37 不清空的话，支付方式会累加。
            if (feePayTypeListBeanArrayListDatas != null) {
                feePayTypeListBeanArrayListDatas.clear();
            }

//                        ArrayList<FeePayTypeListBean> feePayTypeListBeanArrayList = paymentFeeBean.getPayTypes();
            ArrayList<FeePayTypeListBean> feePayTypeListBeanArrayList = _paymentFeeBean.getPayTypes();

            if (feePayTypeListBeanArrayList != null && !feePayTypeListBeanArrayList.isEmpty()) {

                if (feePayTypeListBeanArrayListDatas != null) {
                    feePayTypeListBeanArrayListDatas.addAll(feePayTypeListBeanArrayList);
                }

            }
            //----------------------------------------------------------------------------------------------------
            //物业缴费的待缴费列表信息
            ArrayList<PropertyPaymentBean> propertyPaymentBeanArrayList = _paymentFeeBean.getHousePayments();

            if (propertyPaymentBeanArrayList != null && !propertyPaymentBeanArrayList.isEmpty()) {

                if (mDatasResources != null) {
                    mDatasResources.addAll(propertyPaymentBeanArrayList);
                }

            }
            //---------------------------------------------------------------------------------------------------

        }

        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
        if (mDatasResources != null && mDatasResources.isEmpty()) {
            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
        }

        if (propertyPaymentAdapter != null) {
            propertyPaymentAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadEventPayProperFee(EventPay eventPay) {

        if (eventPay != null) {

            int errorCode = eventPay.getMessage();
            //isOpenWechart = false;//itchen retain先这样，等调试接口再处理

            if (errorCode == BaseResp.ErrCode.ERR_OK) {

                //获取服务器端告知支付成功的接口,然后跳转到结算结果页。
//                gainOrderState(payTokenForPay, 1);
                method_handler_success_for_alipayOrweChat();

            } else if (errorCode == BaseResp.ErrCode.ERR_USER_CANCEL) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付取消");
//                ToastUtils.showShort("支付取消");
                //2018年03月20日逻辑，微信支付失败仍然停留在此界面。
                //gainOrderStateFail(payTokenForPay,0);
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.pop_pay_cancel));

            } else if (errorCode == BaseResp.ErrCode.ERR_AUTH_DENIED) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付失败");
//                ToastUtils.showShort("支付失败");

                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_failed));


            } else if (errorCode == BaseResp.ErrCode.ERR_COMM) {

                //LogUtils.d("itchen-----执行微信支付错误逻辑");
//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付错误");
//                ToastUtils.showShort("支付错误");

                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_wrong));

                //gainOrderStateFail(payTokenForPay,0);
            } else if (errorCode == BaseResp.ErrCode.ERR_SENT_FAILED) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "支付发送失败");
//                ToastUtils.showShort("支付发送失败");

                //gainOrderStateFail(payTokenForPay,0);
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_send_message_fail));

            } else if (errorCode == BaseResp.ErrCode.ERR_UNSUPPORT) {

//                CommUtils.displayToastShort(PaintBookingFeeActivity.this, "不支持错误");
//                ToastUtils.showShort("不支持错误");
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_not_supported_wrong));

                //gainOrderStateFail(payTokenForPay,0);

            } else {
                //retain
//                ToastUtils.showShort("未知错误");
                ToastUtils.showShort(mActivityInstance.getResources().getString(R.string.wechat_pay_unkown_wrong));
            }


        }

    }


    //支付完毕处理 微信支付成功信息
    private void method_handler_success_for_alipayOrweChat() {

        //通知物业缴费的外侧主页列表刷新-,给已经支付的那条数据给刷新掉
        EventBus.getDefault().post(new EventPaymentSubmint(ExtraValue.EVENTBUS_EVENTPAYMENTSUBMINT));

        methodSingleSubmitSuccessCustomTitle(PaymentFeeActivity.this, getString(R.string.alipay_pay_success), new DoSomeThingListener() {

            @Override
            public void doSomeThing() {

                //物业缴费结算完毕，该页面关闭。
                methodBack();

            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (basePopupView_payType != null) {
            basePopupView_payType.onDestroy();
            basePopupView_payType = null;
        }

        //该页面没有微信支付等；
        if (mWinXinApi != null) {
            mWinXinApi = null;
        }

        if (housePaymentIdsPass != null && !housePaymentIdsPass.isEmpty()) {
            housePaymentIdsPass.clear();
            housePaymentIdsPass = null;
        }

        if (mDatasResources != null && !mDatasResources.isEmpty()) {
            mDatasResources.clear();
//            mDatasResources = null;
        }

        if (propertyPaymentAdapter != null) {
            propertyPaymentAdapter.notifyDataSetChanged();
            propertyPaymentAdapter = null;
        }

        if (mDatasResources != null) {
            mDatasResources = null;
        }

        EventBus.getDefault().unregister(this);

    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

//            priceTotal = bundle.getString(ExtraKey.EXTRA_PAYMENT_AMOUNT);

            housePaymentIdsPass = bundle.getStringArrayList(ExtraKey.EXTRA_PAYMENT_HOUSEPAYMENTIDS);

            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "携带的id信息长度是->" + housePaymentIdsPass.size());

//            station_shopId_upLoad = bundle.getString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID);
            //这个特殊，采用同一个对象；
            //服务站的顶部选择列表---这里取到的肯定是空值，因为上一个页面没有携带
//            extra_assetStationInfoListForAddAsset_loacalDB = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET);
            //资产的归属方 列表，
//            extra_assetUnderBusinessInfoListOutSide = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE);

        }
    }

    /**
     * 支付宝支付
     */
    private void method_paymentAlipaySDK(final AlipayPayBean _alipayPayBean) {

        try {

            //do

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(PaymentFeeActivity.this);
                    Map<String, String> result = alipay.payV2(_alipayPayBean.getPayInfo(), true);
                    //Log.i("msp", result.toString());

                    //2023年1月31日13:50:44-bugly抓到
                    //java.lang.NullPointerException
                    //PaymentFeeActivity$BetterHandlerInPaymentFee.sendMessage(android.os.Message)' on a null object reference
                    Message msg = new Message();
                    if (msg != null) {
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);

                    } else {

//                    CommUtils.displayToastShort(mActivityInstance, "发送消息出错~");
                        ToastUtils.showShort(getResources().getString(R.string.alipay_pay_send_message_error));

                    }
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();

        } catch (Exception e) {
            //catch

            if (e != null) {
                ToastUtils.showShort(getResources().getString(R.string.alipay_error_info) + getResources().getString(R.string.wechat_error_info) + e.getMessage());
            } else {
                ToastUtils.showShort(getResources().getString(R.string.alipay_error_info));
            }

            e.printStackTrace();
        }


    }

    //处理微信支付的逻辑
    private void method_paymentWeChatSDK(final WechatPayBean _wechatPayBean) {

        try {

            //检测微信客户端是否安装
            if (mWinXinApi != null) {

                if (mWinXinApi.isWXAppInstalled()) {

                    //LogUtils.d("itchen-----微信支付内部 method_paymentWeChatSDK ");

                    PayReq req = new PayReq();
                    //原始代码
                    req.appId = _wechatPayBean.getAppid();
                    req.partnerId = _wechatPayBean.getPartnerid();//json.getString("partnerid");
                    req.prepayId = _wechatPayBean.getPrepayid();//json.getString("prepayid");
                    req.nonceStr = _wechatPayBean.getNoncestr();//json.getString("noncestr");
                    req.timeStamp = _wechatPayBean.getTimestamp();//json.getString("timestamp");
                    req.packageValue = _wechatPayBean.getPkg();//json.getString("package");
                    req.sign = _wechatPayBean.getSign();//json.getString("sign");
                    //req.extData = "app data"; // optional//额外携带信息暂时不处理

                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    mWinXinApi.sendReq(req);

                } else {
                    CommUtils.method_showAlert(PaymentFeeActivity.this, getResources().getString(R.string.not_install_wechat), mAlertView);
                }
            }

        } catch (Exception e) {

            //微信本身的异常 仍然停留在该界面，让他勾选其他支付方式。
            if (e != null) {
                ToastUtils.showShort(getResources().getString(R.string.wechat_error) + getResources().getString(R.string.wechat_error_info) + e.getMessage());
            } else {
                ToastUtils.showShort(getResources().getString(R.string.wechat_error));
            }

        }

    }


    //调用支付方式获取微信支付或者支付宝支付启动数据
    private void methd_to_payMent_WeChatSDK_or_AlipaySDK_type_property(String _payType) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//        map.put(Parameterkey.payType, _payType);//支付方式 水费电费的缴费方式
        map.put(Parameterkey.beforeReceiptNo, beforeReceiptNo);//支付的预付单号
//        map.put(Parameterkey.appSource, "");//APP的来源 COMMUNITYSTEWARD 区分 数字社区 DIGITALCOMMUNITY
        map.put(Parameterkey.payTypeCode, _payType);//物业缴费的支付方式
//        map.put(Parameterkey.userToken, MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN));//用户的token


        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETGAUGEPAYINFO_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getGaugePayInfo_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .saveReceiptAndPayForRemote(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(FeeWaterFragment.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PayParameterResult>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        CommUtils.checkMaterialDialog(materialDialog);
//                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(PaymentFeeActivity.this, ConstantSign.TIPS_LOADING);

                    }
                }).subscribe(new Consumer<PayParameterResult>() {
                    @Override
                    public void accept(PayParameterResult payParameterResultValue) throws Throwable {

                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "看看是在哪个线程---subscribe---accept");
                        //main, com.ygxsk.carhome.ui.livefee.PaymentFeeActivity$14.accept(PaymentFeeActivity.java:1184)
                        //itchen-->看看是在哪个线程---subscribe--subscribe--accept

                        CommUtils.checkMaterialDialog(materialDialog);

                        // TODO: 2023-12-21 15:32 调用支付宝支付的接口
                        if (TextUtils.equals(_payType, FeePayType.TYPE_ALIPAY.getPayTypeCode())) {

                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                method_handler_alipay_SDK_for_nomal(payParameterResultValue);

                            } else {

                                method_handler_alipay_SDK_for_moreAndroid13(payParameterResultValue);

                            }

                        } else if (TextUtils.equals(_payType, FeePayType.TYPE_WECHAT.getPayTypeCode())) {


                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                method_handler_wechat_SDK_for_nomal(payParameterResultValue);

                            } else {

                                method_handler_wechat_SDK_for_moreAndroid13(payParameterResultValue);

                            }

                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //页面报错；
                        if (apiException != null) {

                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }

                        }

                    }
                });

    }

    //支付宝支付的正常逻辑
    private void method_handler_alipay_SDK_for_nomal(PayParameterResult payParameterResultValue) {

        //有权限设置
        if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_PHONE_STATE)//
                || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    //2018年11月22日发现支付宝需要添加权限
                    AndPermission.with(PaymentFeeActivity.this)
                            .runtime()
                            .permission(Permission.READ_PHONE_STATE,//
                                    Permission.WRITE_EXTERNAL_STORAGE,//
                                    Permission.READ_EXTERNAL_STORAGE)
                            .rationale(new RuntimeRationale())
                            .onGranted(new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> data) {

                                    LogUtils.d("itchen---->执行调用 method_paymentAlipaySDK---支付宝支付");

                                    //支付宝SDK调起
                                    method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());

                                }
                            }).onDenied(new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> permissions) {
                                    if (AndPermission.hasAlwaysDeniedPermission(PaymentFeeActivity.this, permissions)) {
                                        (new PermissionSetting(PaymentFeeActivity.this)).showSetting(ConstantApi.PERMISSION_NORMAL, PaymentFeeActivity.this, permissions);
                                    }
                                }
                            }).start();
                }
            });

        } else {
            //支付宝SDK调起
            method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());
        }


    }

    //支付宝 支付 大于android13的使用
    private void method_handler_alipay_SDK_for_moreAndroid13(PayParameterResult payParameterResultValue) {

        //高于android13的版本。
        //有权限设置
        if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.READ_PHONE_STATE)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    XXPermissions.with(PaymentFeeActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
                            .permission(com.hjq.permissions.Permission.READ_PHONE_STATE)//
//                              .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过

                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(PaymentFeeActivity.this, permissions)));

                                    //支付宝SDK调起
                                    method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());

                                }
                            });
                }

            });

        } else {
            //支付宝SDK调起
            method_paymentAlipaySDK(payParameterResultValue.getAlipayPay());
        }

    }

    //微信支付-正常版本的支付
    private void method_handler_wechat_SDK_for_nomal(PayParameterResult payParameterResultValue) {

        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--打开的是普通的-微信支付--method_handler_wechat_SDK_for_nomal");

        //有权限设置
        if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_PHONE_STATE)//
                || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    //2018年11月22日发现支付宝需要添加权限
                    AndPermission.with(PaymentFeeActivity.this)
                            .runtime()
                            .permission(Permission.READ_PHONE_STATE,//
                                    Permission.WRITE_EXTERNAL_STORAGE,//
                                    Permission.READ_EXTERNAL_STORAGE)
                            .rationale(new RuntimeRationale())
                            .onGranted(new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> data) {

                                    LogUtils.d("itchen---->执行调用 method_paymentWeChatSDK---微信支付");

                                    //支付宝SDK调起
                                    method_paymentWeChatSDK(payParameterResultValue.getWechatPay());

                                }
                            }).onDenied(new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> permissions) {
                                    if (AndPermission.hasAlwaysDeniedPermission(PaymentFeeActivity.this, permissions)) {
                                        (new PermissionSetting(PaymentFeeActivity.this)).showSetting(ConstantApi.PERMISSION_NORMAL, PaymentFeeActivity.this, permissions);
                                    }
                                }
                            }).start();
                }
            });

        } else {
            //微信SDK调起
            method_paymentWeChatSDK(payParameterResultValue.getWechatPay());
        }
    }

    //是租赁费的支付过来的
    private void methd_to_payMent_WeChatSDK_or_AlipaySDK_type_rental(String _payType) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//        map.put(Parameterkey.payType, _payType);//支付方式 水费电费的缴费方式
        map.put(Parameterkey.beforeReceiptNo, beforeReceiptNo);//支付的预付单号
//        map.put(Parameterkey.appSource, "");//APP的来源 COMMUNITYSTEWARD 区分 数字社区 DIGITALCOMMUNITY
        map.put(Parameterkey.payTypeCode, _payType);//物业缴费的支付方式
//        map.put(Parameterkey.userToken, MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN));//用户的token
//        map.put(Parameterkey.couponCustomerId, );

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_SAVERECEIPTANDPAY_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.saveReceiptAndPay_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .saveReceiptAndPay(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(FeeWaterFragment.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PayParameterResult>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

//                        CommUtils.checkMaterialDialog(materialDialog);
//                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

//                        CommUtils.checkMaterialDialog(materialDialog);
//                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);

                    }
                }).subscribe(new Consumer<PayParameterResult>() {
                    @Override
                    public void accept(PayParameterResult payParameterResultValue) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        // TODO: 2023-12-21 15:32 调用支付宝支付的接口
                        if (TextUtils.equals(_payType, FeePayType.TYPE_ALIPAY.getPayTypeCode())) {

                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                method_handler_alipay_SDK_for_nomal(payParameterResultValue);

                            } else {

                                //高于android13的版本。
                                method_handler_alipay_SDK_for_moreAndroid13(payParameterResultValue);

                            }

                        } else if (TextUtils.equals(_payType, FeePayType.TYPE_WECHAT.getPayTypeCode())) {


                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                //有权限设置
                                method_handler_wechat_SDK_for_nomal(payParameterResultValue);

                            } else {

                                method_handler_wechat_SDK_for_moreAndroid13(payParameterResultValue);

                            }
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

//                        CommUtils.checkMaterialDialog(materialDialog);

                        function_apiException(apiException);

                        //页面报错；
//                        if (apiException != null) {
//                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
//                                ToastUtils.showShort(apiException.getDisplayMessage());
//                            }
//                        }

                    }
                });

    }

    //微信支付 的android版本大于android13的处理
    private void method_handler_wechat_SDK_for_moreAndroid13(PayParameterResult payParameterResultValue) {

        if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.READ_PHONE_STATE)) {//

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_PHONESTATE, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    XXPermissions.with(PaymentFeeActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
                            .permission(com.hjq.permissions.Permission.READ_PHONE_STATE)//
                            //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
//                                                        .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过
                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(PaymentFeeActivity.this, permissions)));

                                    method_paymentWeChatSDK(payParameterResultValue.getWechatPay());

                                }
                            });
                }
            });

        } else {

            //微信支付调起
            method_paymentWeChatSDK(payParameterResultValue.getWechatPay());

        }
    }


}